package com.dotools.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;

import java.util.HashSet;

public class LauncherAfterInstalled {
  private Context mAppContext;
  private BroadcastReceiver mBroadcastReceiver;
  private HashSet<String> mPackageLists;

  private LauncherAfterInstalled(Context context) {
    this.mAppContext = context.getApplicationContext();
  }

  private static LauncherAfterInstalled launcherAfterInstalled;

  public static LauncherAfterInstalled getInstance(Context context) {
    if (launcherAfterInstalled == null) {
      launcherAfterInstalled = new LauncherAfterInstalled(context);
    }
    return launcherAfterInstalled;
  }

  public void monitor(String packageName) {
    if (packageName == null) {
      throw new RuntimeException("packageName must be not null");
    }
    if (mBroadcastReceiver == null) {
      mBroadcastReceiver = new InstalledReceiver();
      IntentFilter intentFilter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
      intentFilter.addDataScheme("package");
      mAppContext.registerReceiver(mBroadcastReceiver, intentFilter);
      mPackageLists = new HashSet<>();
    }
    mPackageLists.add(packageName);
  }

  private void checkStopMonitor() {
    if (mPackageLists.size() == 0) {
      stopMonitor();
    }
  }

  private void stopMonitor() {
    mAppContext.unregisterReceiver(mBroadcastReceiver);
    mBroadcastReceiver = null;
    mPackageLists = null;
  }

  class InstalledReceiver extends BroadcastReceiver {

    @Override public void onReceive(Context context, Intent intent) {
      if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) {
        String packageName = intent.getData().getEncodedSchemeSpecificPart();
        if (mPackageLists.contains(packageName)) {
          mPackageLists.remove(packageName);
          PackageManager packageManager = context.getPackageManager();
          Intent launchIntent = packageManager.getLaunchIntentForPackage(packageName);
          launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          mAppContext.startActivity(launchIntent);
        }
        checkStopMonitor();
      }
    }
  }
}
